package com.atguigu.guilimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.guilimall.cart.config.MyThirdConfig;
import com.atguigu.guilimall.cart.feign.ProductFeignService;
import com.atguigu.guilimall.cart.interceptor.CartInterceptor;
import com.atguigu.guilimall.cart.service.CartService;
import com.atguigu.guilimall.cart.vo.Cart;
import com.atguigu.guilimall.cart.vo.CartItem;
import com.atguigu.guilimall.cart.vo.SkuInfoVo;
import com.atguigu.guilimall.cart.vo.UserInfoTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    ThreadPoolExecutor excetors;
    private static final String CART_PREFIX = "mall:cart:";

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String sku = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(sku)) {
            CartItem item = new CartItem();
            //1.远程查询要添加购物车的商品的sku信息
            CompletableFuture<Void> getSkuInfo = CompletableFuture.runAsync(() -> {
                R data = productFeignService.getSkuInfo(skuId);
                SkuInfoVo skuInfo = data.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                //2.将商品封装到购物车
                item.setCheck(true);
                item.setImage(skuInfo.getSkuDefaultImg());
                item.setCount(num);
                item.setTitle(skuInfo.getSkuTitle());
                item.setPrice(skuInfo.getPrice());
                item.setSkuId(skuInfo.getSkuId());
            }, excetors);
            CompletableFuture<Void> getAttrSaleValues = CompletableFuture.runAsync(() -> {
                List<String> attrValue = productFeignService.getAttrValue(skuId);
                item.setSkuAttr(attrValue);

            }, excetors);
            CompletableFuture.allOf(getSkuInfo, getAttrSaleValues).get();
            String jsonString = JSON.toJSONString(item);
            cartOps.put(skuId.toString(), jsonString);
            return item;
        } else {
            //购物车有此商品
            CartItem item = JSON.parseObject(sku, CartItem.class);
            item.setCount(item.getCount() + num);
            cartOps.put(skuId.toString(), JSON.toJSONString(item));
            return item;
        }
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String key = (String) cartOps.get(skuId.toString());
        CartItem item = JSON.parseObject(key, CartItem.class);
        return item;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String tempUserKey = CART_PREFIX+userInfoTo.getUserKey();
        if (userInfoTo.getUserId()!=null){
            //判断是否存在临时购物车
            List<CartItem> tempCartItems = getCartItems(tempUserKey);
            if (tempCartItems!=null){
                for (CartItem tempCartItem : tempCartItems) {
                    addToCart(tempCartItem.getSkuId(),tempCartItem.getCount());
                }
                clearCart(tempUserKey);
            }
            //登录,获取登录的购物车
            String userKey = CART_PREFIX+ userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(userKey);


            cart.setItems(cartItems);

        }else {

            //未登录,取临时购物车
            List<CartItem> cartItems = getCartItems(tempUserKey);
            cart.setItems(cartItems);
        }

        return cart;
    }

    /**
     *
     * @param cartKey 用户的秘钥
     * @Descript
     * 清空用户的购物车
     *
     */
    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void check(Long skuId, Long check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        String jsonString = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cartOps1 = getCartOps();
        cartOps1.put(skuId.toString(),jsonString);
    }

    @Override
    public void countItem(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String jsonString = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),jsonString);

    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {

        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo==null){
            return null;
        }else {
            List<CartItem> cartItems = getCartItems(CART_PREFIX + userInfoTo.getUserId().toString());
            List<CartItem> result = cartItems.stream().filter(item -> {
                Long skuId = item.getSkuId();
                R data = productFeignService.getPrice(skuId);
                String price = (String) data.get("data");
                item.setPrice(new BigDecimal(price));
                return item.getCheck() == true;
            }).collect(Collectors.toList());
            return result;
        }
    }

    /**
     *
     * @param tempUserKey 用户的key
     * @return
     * cartItems 购物车信息
     * @Descript
     * 根据用户获取当前购物车商品信息
     *
     */
    private List<CartItem> getCartItems(String tempUserKey) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(tempUserKey);
        if (hashOps.values()!=null){
            List<CartItem> cartItems = hashOps.values().stream().map(obj -> {
                String s = obj.toString();
                CartItem item = JSON.parseObject(s, CartItem.class);
                return item;
            }).collect(Collectors.toList());
            return cartItems;
        }else {
            return null;
        }

    }

    /**
     * 获取要操作的购物车
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            //登录
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        return hashOps;
    }

}
